package com.meichis.yndms.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.meichis.mcsappframework.dialog.DropDownDialog;
import com.meichis.mcsappframework.http.CallManager;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.mcsappframework.utils.Tools;
import com.meichis.yndms.R;
import com.meichis.yndms.common.APIWEBSERVICE;
import com.meichis.yndms.common.MCode;
import com.meichis.yndms.databinding.ActivityDebugBinding;

import com.meichis.yndms.repository.manager.AppUpdataManager;
import com.meichis.yndms.repository.manager.LoginRequestManager;
import com.meichis.yndms.repository.manager.TokenManager;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.AppUpdateVM;
import com.meichis.yndms.vm.LoginVM;

import java.lang.ref.WeakReference;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;


public class DebugActivity extends BaseActivity {

    ActivityDebugBinding binding;
    private LoginVM vm;
    private AppUpdateVM appUpdateVM;
    private String doMain;
    private MyHandler myHandler;

    private boolean isOtehrUrl = false;
    private String otherUrl;

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_debug);
        vm = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(LoginVM.class);
        appUpdateVM = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(AppUpdateVM.class);
        binding.setVm(vm);
        binding.setClick(new ClickEvent());


        String remote = util.getStringValue(MCode.PREFERENCES_REMOTE);
        binding.btChange.setText(TextUtils.isEmpty(remote) || remote.startsWith("https://sfa.yili.com") ? "sfa.yili.com" : remote.startsWith("https://sfalt.yili.com") ? "sfalt.yili.com" : "其他");
        if (binding.btChange.getText().equals("sfa.yili.com")) {
            doMain = "https://sfa.yili.com/";
        } else if (binding.btChange.getText().equals("sfalt.yili.com")) {
            doMain = "https://sfalt.yili.com/";
        } else {
            doMain = remote;
        }
        binding.etRemoteURL.setText(APIWEBSERVICE.REMOTE_MCSWSIAPI);
        myHandler = new MyHandler(binding);

    }

    @Override
    protected void init() {
        binding.navigation.txtTitle.setText("网络设置");
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());

        addObserver();
    }

    private void addObserver() {

        vm.getDspToken().observe(this, dspToken -> {
            if (dspToken != null) {
                binding.tvInfo.append("登录信息：获取成功" + "\n");
                util.setCacheValue(SharePreferenceUtil.PREFERENCES_AUTHKEY, vm.getDspToken().getValue().getAccess_token(), vm.getDspToken().getValue().getExpires_in() / 60);
                TokenManager.setToken();
                util.setCacheValue(SharePreferenceUtil.PREFERENCES_REFRESHAUTHKEY, vm.getDspToken().getValue().getRefresh_token(), 30 * 60 * 24);
                binding.tvInfo.append("获取APP版本信息中....\n");
                appUpdateVM.GetLastVersionAndErrorInfo();
            }
        });

        vm.getErrorData().observe(this, error -> {
            if (!TextUtils.isEmpty(error)) {
                binding.tvInfo.append("登录报错：" + error + "\n");
                if (isOtehrUrl) {//如果其他网址访问失败，把baseUrl切回到上一次选择的
                    String remote = util.getStringValue(MCode.PREFERENCES_REMOTE);  //读取保存的网络设置地址
                    if (TextUtils.isEmpty(remote) || remote.equals(otherUrl)) {
                        remote = "https://sfa.yili.com/";
                    }
                    APIWEBSERVICE.REMOTE_MCSWSIAPI = remote;
                }
            }
        });

        appUpdateVM.getAppVersion().observe(this, appVersion -> {
            if (appVersion != null) {
                //清除登录信息
                SharePreferenceUtil.getInstance().remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
                binding.tvInfo.append("版本信息：获取成功\n");
                if (isOtehrUrl) {//登录成功后app后续请求使用该地址
                    APIWEBSERVICE.REMOTE_MCSWSIAPI = otherUrl;
                    util.setStringValue(MCode.PREFERENCES_REMOTE, APIWEBSERVICE.REMOTE_MCSWSIAPI);
                }
            }
        });

        appUpdateVM.getAppErrorData().observe(this, errorInfo -> {
            if (!TextUtils.isEmpty(errorInfo)) {
                //清除登录信息
                SharePreferenceUtil.getInstance().remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
                binding.tvInfo.append("获取版本信息报错：" + errorInfo + "\n");
                if (isOtehrUrl) {//如果其他网址访问失败，把baseUrl切回到上一次选择的
                    String remote = util.getStringValue(MCode.PREFERENCES_REMOTE);  //读取保存的网络设置地址
                    if (TextUtils.isEmpty(remote) || remote.equals(otherUrl)) {
                        remote = "https://sfa.yili.com/";
                    }
                    APIWEBSERVICE.REMOTE_MCSWSIAPI = remote;
                }
            }
        });
    }

    private static class MyHandler extends Handler {
        private final WeakReference<ActivityDebugBinding> mActivityWeakReference;

        private MyHandler(ActivityDebugBinding binding) {
            mActivityWeakReference = new WeakReference<ActivityDebugBinding>(binding);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mActivityWeakReference.get() == null) {
                return;
            }
            if (msg.what == 0) {
                Bundle bundle = msg.getData();
                String address = bundle.getString("address");
                ActivityDebugBinding binding = mActivityWeakReference.get();
                binding.tvInfo.append("请求地址对应IP为：" + address + "\n");
                binding.tvInfo.append("登录中....\n");
                binding.getVm().LoginTest();
            }

        }
    }

    public void GetInetAddress(String host) {
        host = host.substring(host.indexOf("//") + 2, host.indexOf(".com") + 4);
        String finalHost = host;
        new Thread(() -> {
            Message message = new Message();
            message.what = 0;
            Bundle bundle = new Bundle();
            try {
                InetAddress ReturnStr1 = InetAddress.getByName(finalHost);
                String IPAddress = ReturnStr1.getHostAddress();
                bundle.putString("address", IPAddress);
                message.setData(bundle);
                myHandler.sendMessage(message);
            } catch (UnknownHostException e) {
                e.printStackTrace();
                bundle.putString("address", "");
                message.setData(bundle);
                myHandler.sendMessage(message);
            }
        }).start();

    }


    public class ClickEvent {

        public void changeRequestUrl() {
            final ArrayList<String> list = new ArrayList<>();
            list.add("sfa.yili.com");
            list.add("sfalt.yili.com");
            list.add("其他");
            new DropDownDialog<>(DebugActivity.this, R.color.theme, "切换网络", "", list, (o, position) -> {
                switch (position) {
                    case 0:
                        binding.etRemoteURL.setVisibility(View.VISIBLE);
                        binding.llOther.setVisibility(View.GONE);
                        doMain = "https://sfa.yili.com/";
                        isOtehrUrl = false;
                        util.setStringValue(MCode.PREFERENCES_REMOTE, doMain);
                        break;
                    case 1:
                        binding.etRemoteURL.setVisibility(View.VISIBLE);
                        binding.llOther.setVisibility(View.GONE);
                        doMain = "https://sfalt.yili.com/";
                        isOtehrUrl = false;
                        util.setStringValue(MCode.PREFERENCES_REMOTE, doMain);
                        break;
                    case 2:
                        binding.etRemoteURL.setVisibility(View.GONE);
                        binding.llOther.setVisibility(View.VISIBLE);
                        isOtehrUrl = true;
                        doMain = "yili.com/";
                        binding.etOtherURL.setText("");
                        break;
                    default:
                        break;
                }
                binding.etRemoteURL.setText(doMain);
                binding.btChange.setText(list.get(position));
            }).show();
        }

        public void requestTest() {
            binding.tvInfo.setText("");
            if (isOtehrUrl) {
                otherUrl = "https://" + binding.etOtherURL.getText().toString().trim() + doMain;
                if (TextUtils.isEmpty(binding.etOtherURL.getText())) {
                    MessageTools.showShortToast("请输入请求地址");
                    return;
                }
                APIWEBSERVICE.REMOTE_MCSWSIAPI = otherUrl;
            } else {
                APIWEBSERVICE.REMOTE_MCSWSIAPI = doMain;
            }

            binding.tvInfo.append("当前网络：" + Tools.getNetType(DebugActivity.this) + "\n");
            binding.tvInfo.append("本机IP：" + Tools.getLocalIpAddress() + "\n");
            binding.tvInfo.append("DNS解析中....\n");
            GetInetAddress(APIWEBSERVICE.REMOTE_MCSWSIAPI);

        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        SharePreferenceUtil.getInstance().remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
        myHandler.removeCallbacksAndMessages(null);
        //销毁时重置rootApi
        LoginRequestManager.getInstance().clearInstance();
        AppUpdataManager.getInstance().clearInstance();
    }
}
